package com.uzai.console.service.profit.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.profit.inviterewardrule.InviteRewardRuleIdDto;
import com.uzai.console.dto.profit.inviterewardrule.InviteRewardRuleInfoDto;
import com.uzai.console.dto.profit.inviterewardrule.InviteRewardRuleQuery;
import com.uzai.console.dto.profit.regrewardrule.RegRewardRuleQuery;
import com.uzai.console.entity.InviteRewardRule;
import com.uzai.console.entity.RegRewardRule;
import com.uzai.console.mapper.InviteRewardRuleMapper;
import com.uzai.console.mapper.RegRewardRuleMapper;
import com.uzai.console.service.profit.InviteRewardRuleService;
import com.uzai.console.vo.profit.inviterewardrule.InviteRewardRuleInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * @author liuqi
 * @date 2021年09月01日 19:26
 */
@Service
public class InviteRewardRuleServiceImpl implements InviteRewardRuleService {

    @Autowired
    private InviteRewardRuleMapper inviteRewardRuleMapper;
    @Autowired
    private RegRewardRuleMapper regRewardRuleMapper;
    
    /**
     * 分页查询邀请奖励列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param query
     * @return null
     */
    public Page<InviteRewardRuleInfoVo> findInviteRewardRuleList(InviteRewardRuleQuery query){
        //新建返回到页面的LIST对象
        List<InviteRewardRuleInfoVo> inviteRewardRuleInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<InviteRewardRule> page = new Page<>();
        query.convert(page);
        List<InviteRewardRule> inviteRewardRuleList = inviteRewardRuleMapper.findByList(page, query);

        if(inviteRewardRuleList != null){
            for (InviteRewardRule inviteRewardRule : inviteRewardRuleList){
                InviteRewardRuleInfoVo inviteRewardRuleInfoVo = new InviteRewardRuleInfoVo();
                BeanUtils.copyProperties(inviteRewardRule, inviteRewardRuleInfoVo);
                inviteRewardRuleInfoVoList.add(inviteRewardRuleInfoVo);
            }
        }

        //返回到页面分页对象
        Page<InviteRewardRuleInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(inviteRewardRuleInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询邀请奖励详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param inviteRewardRuleIdDto
     * @return null
     */
    public InviteRewardRuleInfoVo findInviteRewardRuleInfo(InviteRewardRuleIdDto inviteRewardRuleIdDto){
        if(inviteRewardRuleIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        InviteRewardRule inviteRewardRule = inviteRewardRuleMapper.selectById(inviteRewardRuleIdDto.getId(), inviteRewardRuleIdDto.getMerId());

        if(inviteRewardRule == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该邀请奖励不存在");
        }

        InviteRewardRuleInfoVo inviteRewardRuleInfoVo =  new InviteRewardRuleInfoVo();

        BeanUtils.copyProperties(inviteRewardRule, inviteRewardRuleInfoVo);

        return inviteRewardRuleInfoVo;
    }

    /**
     * 添加邀请奖励
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param inviteRewardRuleInfoDto
     * @return null
     */
    public void addInviteRewardRule(InviteRewardRuleInfoDto inviteRewardRuleInfoDto){
        if(StringUtils.isBlank(inviteRewardRuleInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "邀请奖励名称不能为空");
        }
        if(StringUtils.isBlank(inviteRewardRuleInfoDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "邀请奖励数据不能为空");
        }

        JSONObject jsonObject = JSONObject.parseObject(inviteRewardRuleInfoDto.getData());
        if(jsonObject == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "邀请奖励数据不能为空");
        }

        Integer rewardModel = jsonObject.getInteger("reward_model");
        if(rewardModel == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "奖励模式不能为空");
        }

        InviteRewardRule inviteRewardRule_name = inviteRewardRuleMapper.selectByNameAndMerId(inviteRewardRuleInfoDto.getName(), inviteRewardRuleInfoDto.getMerId());
        if(inviteRewardRule_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
        }

        if(rewardModel.intValue() == 0){ //按照好友人数
            JSONArray reg_reward_rules = jsonObject.getJSONArray("reg_reward_rules");
            if(reg_reward_rules == null || reg_reward_rules.size() <= 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请添加一条规则");
            }
            //验证是否重复
            List<Integer> countHashMap = new ArrayList<>();
            for (int i = 0; i<reg_reward_rules.size(); i++) {
                JSONObject reg_reward =  reg_reward_rules.getJSONObject(i);
                Integer invite_count = reg_reward.getInteger("invite_count");
                //包含
                if(countHashMap.contains(invite_count)){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "规则重复");
                }else{
                    countHashMap.add(invite_count);
                }
            }
        }else if(rewardModel.intValue() == 1){
            JSONArray order_reward_rules = jsonObject.getJSONArray("order_reward_rules");
            if(order_reward_rules == null || order_reward_rules.size() <= 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请添加一条规则");
            }
            //验证是否重复
            List<Integer> countHashMap = new ArrayList<>();
            for (int i = 0; i<order_reward_rules.size(); i++) {
                JSONObject order_reward =  order_reward_rules.getJSONObject(i);
                Integer order_user_count = order_reward.getInteger("order_user_count");
                //包含
                if(countHashMap.contains(order_user_count)){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "人数规则重复");
                }else{
                    countHashMap.add(order_user_count);
                }
            }
        }

        InviteRewardRule inviteRewardRule =  new InviteRewardRule();
        BeanUtils.copyProperties(inviteRewardRuleInfoDto, inviteRewardRule);

        Integer now = DateUtil.getNowTime();
        inviteRewardRule.setId(IdWorker.getId());
        inviteRewardRule.setCreateTime(now);
        inviteRewardRule.setUpdateTime(now);
        if(Tools.getInteger(inviteRewardRule.getStartTime()).intValue() == 0 ){//页面没有填写，默认创建时间
            inviteRewardRule.setStartTime(now);
        }
        inviteRewardRuleMapper.insertSelective(inviteRewardRule);
    }

    /**
     * 修改邀请奖励
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param inviteRewardRuleInfoDto
     * @return null
     */
    public void updateInviteRewardRule(InviteRewardRuleInfoDto inviteRewardRuleInfoDto){

        if(inviteRewardRuleInfoDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        if(StringUtils.isBlank(inviteRewardRuleInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "邀请奖励名称不能为空");
        }
        if(StringUtils.isBlank(inviteRewardRuleInfoDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "邀请奖励数据不能为空");
        }

        JSONObject jsonObject = JSONObject.parseObject(inviteRewardRuleInfoDto.getData());
        if(jsonObject == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "邀请奖励数据不能为空");
        }

        Integer rewardModel = jsonObject.getInteger("reward_model");
        if(rewardModel == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "奖励模式不能为空");
        }

        if(rewardModel.intValue() == 0){ //按照好友人数
            JSONArray reg_reward_rules = jsonObject.getJSONArray("reg_reward_rules");
            if(reg_reward_rules == null || reg_reward_rules.size() <= 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请添加一条规则");
            }
            //验证是否重复
            List<Integer> countHashMap = new ArrayList<>();
            for (int i = 0; i<reg_reward_rules.size(); i++) {
                JSONObject reg_reward =  reg_reward_rules.getJSONObject(i);
                Integer invite_count = reg_reward.getInteger("invite_count");
                //包含
                if(countHashMap.contains(invite_count)){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "规则重复");
                }else{
                    countHashMap.add(invite_count);
                }
            }
        }else if(rewardModel.intValue() == 1){
            JSONArray order_reward_rules = jsonObject.getJSONArray("order_reward_rules");
            if(order_reward_rules == null || order_reward_rules.size() <= 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请添加一条规则");
            }
            //验证是否重复
            List<Integer> countHashMap = new ArrayList<>();
            for (int i = 0; i<order_reward_rules.size(); i++) {
                JSONObject order_reward =  order_reward_rules.getJSONObject(i);
                Integer order_user_count = order_reward.getInteger("order_user_count");
                //包含
                if(countHashMap.contains(order_user_count)){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "人数规则重复");
                }else{
                    countHashMap.add(order_user_count);
                }
            }
        }

        InviteRewardRule inviteRewardRule = inviteRewardRuleMapper.selectById(inviteRewardRuleInfoDto.getId(), inviteRewardRuleInfoDto.getMerId());

        if(inviteRewardRule == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此邀请奖励不存在");
        }

        //验证新名字是否已经存在
        if(!inviteRewardRule.getName().equals(inviteRewardRuleInfoDto.getName())){ //表示修改了名称
            //验证新名称是否存在
            InviteRewardRule inviteRewardRule_name = inviteRewardRuleMapper.selectByNameAndMerId(inviteRewardRuleInfoDto.getName(), inviteRewardRuleInfoDto.getMerId());
            if(inviteRewardRule_name != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
            }
        }

        inviteRewardRule.setName(inviteRewardRuleInfoDto.getName());
        inviteRewardRule.setData(inviteRewardRuleInfoDto.getData());
        inviteRewardRule.setUpdateTime(DateUtil.getNowTime());
        inviteRewardRule.setStartTime(Tools.getInteger(inviteRewardRuleInfoDto.getStartTime()));
        inviteRewardRuleMapper.update(inviteRewardRule);

    }

    /**
     * 删除邀请奖励详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param inviteRewardRuleIdDto
     * @return null
     */
    public void deleteInviteRewardRule(InviteRewardRuleIdDto inviteRewardRuleIdDto){
        if(inviteRewardRuleIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        //判断该邀请奖励是否已经在奖励方案中配置
        RegRewardRuleQuery regRewardRuleQuery = new RegRewardRuleQuery();
        regRewardRuleQuery.setMerId(inviteRewardRuleIdDto.getMerId());
        regRewardRuleQuery.setData(String.valueOf(inviteRewardRuleIdDto.getId()));
        List<RegRewardRule> regRewardRuleList = regRewardRuleMapper.findByList(regRewardRuleQuery);
        if(regRewardRuleList != null && regRewardRuleList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该邀请奖励已经在配置方案被占用，不能删除");
        }
        inviteRewardRuleMapper.deleteById(inviteRewardRuleIdDto.getId(), inviteRewardRuleIdDto.getMerId());
    }


}
